import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { logger } from './logger'

// 创建markdown-it实例
const md: MarkdownIt = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str: string, lang: string): string {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return (
          '<pre class="hljs"><code>' +
          hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
          '</code></pre>'
        )
      } catch (error) {
        logger.warn('代码高亮失败:', { error, lang })
      }
    }

    return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>'
  }
})

// 添加常用插件
try {
  // 基础插件
  const emoji = require('markdown-it-emoji')
  const subscript = require('markdown-it-sub')
  const superscript = require('markdown-it-sup')
  const footnote = require('markdown-it-footnote')
  const deflist = require('markdown-it-deflist')
  const abbreviation = require('markdown-it-abbr')
  const insert = require('markdown-it-ins')
  const mark = require('markdown-it-mark')
  const taskLists = require('markdown-it-task-lists')
  
  md.use(emoji.default || emoji)
  md.use(subscript.default || subscript)
  md.use(superscript.default || superscript)
  md.use(footnote.default || footnote)
  md.use(deflist.default || deflist)
  md.use(abbreviation.default || abbreviation)
  md.use(insert.default || insert)
  md.use(mark.default || mark)
  md.use(taskLists.default || taskLists)
  
  // 添加数学公式支持
  const katex = require('markdown-it-katex')
  md.use(katex.default || katex)
  
  logger.info('markdown-it插件加载成功')
} catch (error) {
  logger.warn('部分markdown-it插件加载失败:', error)
}

export default md